package com.rzn.reading.service.impl;

import com.rzn.reading.BeanMapper;
import com.rzn.reading.BusinessException;
import com.rzn.reading.entity.Attach;
import com.rzn.reading.entity.Discussion;
import com.rzn.reading.entity.User;
import com.rzn.reading.mapper.AttachMapper;
import com.rzn.reading.mapper.DiscussionMapper;
import com.rzn.reading.mapper.UserMapper;
import com.rzn.reading.model.dto.discuss.*;
import com.rzn.reading.model.dto.user.UserInfoDTO;
import com.rzn.reading.service.DiscussionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>
 * 讨论区表 服务实现类
 * </p>
 *
 * @author rzn
 * @since 2022-02-12
 */
@Service
public class DiscussionServiceImpl implements DiscussionService {
    @Autowired
    private DiscussionMapper discussionMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AttachMapper attachMapper;

    @Override
    public Boolean insertDiscussion(DiscussionCreateInputDTO discussionCreateInputDTO) {
        Discussion map = BeanMapper.map(discussionCreateInputDTO, Discussion.class);
        return discussionMapper.insert(map) == 1;
    }

    @Override
    public DiscussionCountDTO getDiscussionCount(Integer literatureId) {
        List<Discussion> feeling = discussionMapper.getNumByLiteratureType(literatureId, 0);
        List<Discussion> theme = discussionMapper.getNumByLiteratureType(literatureId, 1);
        List<Discussion> feelPid = feeling.stream().filter(x -> x.getParentId() == 0).collect(Collectors.toList());
        List<Discussion> themePid = theme.stream().filter(x -> x.getParentId() == 0).collect(Collectors.toList());
        DiscussionCountDTO discussionCountDTO = new DiscussionCountDTO(theme.size(), feeling.size(),themePid.size(), feelPid.size());
        return discussionCountDTO;
    }

    @Override
    public List<DiscussionItemDetailDTO> getDiscussItemList(QueryDiscussDTO queryDiscussDTO) {
        List<DiscussionItemDetailDTO> allDiscussion = getAllDiscussion(queryDiscussDTO);
        List<DiscussionItemDetailDTO> all = allDiscussion.stream().filter(m -> m.getParentId() == queryDiscussDTO.getParentId()).map(
                (m) -> {
                    m.setChildList(getChildren(m, allDiscussion));
                    return m;
                }
        ).collect(Collectors.toList());
        //分页
        QueryDiscussionPageParam discussionPageParam = BeanMapper.map(queryDiscussDTO, QueryDiscussionPageParam.class);
        if (queryDiscussDTO.getPage() != null && queryDiscussDTO.getPageSize() != null) {
            discussionPageParam.setOffset((queryDiscussDTO.getPage() - 1) * queryDiscussDTO.getPageSize());
        }
        List<Discussion> discussions = discussionMapper.selectByPage(discussionPageParam);
        discussions.stream().sorted(Comparator.comparing(Discussion::getInsertedAt).reversed());
        List<DiscussionItemDetailDTO> res = new ArrayList<>();
        discussions.forEach(discussion -> {
            Integer id = discussion.getId();
            Optional<DiscussionItemDetailDTO> first = all.stream().filter(x -> x.getId() == id).findFirst();
            if (first.isPresent()) {
                res.add(first.get());
            }
        });
        return res;
    }

    public List<DiscussionItemDetailDTO> getChildren(DiscussionItemDetailDTO root, List<DiscussionItemDetailDTO> all) {
        List<DiscussionItemDetailDTO> children = all.stream().filter(m -> {
            return Objects.equals(m.getParentId(), root.getId());
        }).map(
                (m) -> {
                    m.setChildList(getChildren(m, all));
                    return m;
                }
        ).collect(Collectors.toList());
        return children;
    }

    public List<DiscussionItemDetailDTO> getAllDiscussion(QueryDiscussDTO queryDiscussDTO) {
        List<Discussion> all = discussionMapper.selectAll();
        all.stream().sorted(Comparator.comparing(Discussion::getInsertedAt).reversed());
        List<User> users = userMapper.selectAll();
        List<DiscussionItemDetailDTO> discussionItemDetailDTOS = BeanMapper.mapList(all, DiscussionItemDetailDTO.class);
        List<Attach> attaches = attachMapper.selectByOwnerName("literature_detail");
        discussionItemDetailDTOS.forEach(discussionItemDetailDTO -> {
            //设置url
            Optional<Attach> attach = attaches.stream().filter(x -> x.getOwnerId() == discussionItemDetailDTO.getLiteratureId()).findFirst();
            if (attach.isPresent()) {
                discussionItemDetailDTO.setUrl(attach.get().getUrl());
            }
            //设置发布人信息
            Optional<User> first = users.stream().filter(x -> x.getId() == discussionItemDetailDTO.getUserId()).findFirst();
            if (first.isPresent()) {
                UserInfoDTO map = BeanMapper.map(first.get(), UserInfoDTO.class);
                discussionItemDetailDTO.setUserInfo(map);
            }
        });
        return discussionItemDetailDTOS;
    }

    @Transactional
    @Override
    public Boolean deleteDiscuss(Integer id, Integer userId) {
        Discussion discussion = discussionMapper.selectByPrimaryKey(id);
        if (userId != discussion.getUserId()) {
            throw new BusinessException("对不起，此条记录不是由您创建，您不能删除");
        }
        discussionMapper.deleteByParentId(id);
        return discussionMapper.deleteByPrimaryKey(id) == 1;
    }
}
